package me.ywy.apt.msgimport.main;

import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import me.ywy.apt.msgimport.bean.MsgEntity;
import me.ywy.apt.msgimport.detail.DetailActivity;

/**
 * Created by ywy on 2018-04-16.
 */
public class MainPresenter implements MainContract.Presenter {

    private MainContract.View mView;
    private AppCompatActivity mContext;
    private MainContract.Model mModel;


    private List<MsgEntity> mData;

    public MainPresenter(MainActivity mContext, MainActivity mView) {
        this.mView = mView;
        this.mContext = mContext;
        mModel = new MainModel();
        mData = new ArrayList<>();
    }

    @Override
    public void imputMsg(String inputMsg) {
        String[] split;
        if(inputMsg.contains("、")){
            split = inputMsg.split("、");
        }else{
            split = inputMsg.split("，");
        }
        MsgEntity msgEntity = new MsgEntity();
        StringBuffer stringBuffer = null;
        try {
            msgEntity.setName(split[0]);
            msgEntity.setPhone(split[1]);
            msgEntity.setAddress(split[2]);
            stringBuffer = new StringBuffer();
            if(split.length>4){
                for (int i = 3; i < split.length; i++) {
                    stringBuffer.append(split[i]).append("，");
                }
                if(stringBuffer.charAt(stringBuffer.length()-1) == '，'){
                    stringBuffer.deleteCharAt(stringBuffer.length()-1);
                }
            }else{
                stringBuffer.append(split[3]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mView.showError("数据格式存在问题,请检查");
            return;
        }
        msgEntity.setDesc(stringBuffer.toString());
        mView.convertSuccess();
        mData.add(msgEntity);
        mView.viewRefreach();
    }

    @Override
    public List<MsgEntity> getData() {
        return mData;
    }

    @Override
    public void removeItem(int position) {
        mData.remove(position);
        mView.viewRefreachRemove(position);
    }

    @Override
    public void detailEdit(MsgEntity msgEntity, int position) {
        DetailActivity.startActivityForResult(mContext , msgEntity , position);
    }

    @Override
    public void updateDataListItem(MsgEntity entity, int position) {
        mData.set(position ,entity);
        mView.viewRefreachItem(position);
    }
}
